﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace ZuneLyrics
{
	internal static class LyricsFetcher
	{
		internal static String GetLyrics(String Artist, String Title)
		{
			byte[] responseData;

			string URL;
			string encArtist = System.Web.HttpUtility.UrlEncode(Artist);
			string encTitle = System.Web.HttpUtility.UrlEncode(Title);

			URL = "http://letras.terra.com.br/winamp.php?musica=" + encTitle + "&artista=" + encArtist;

			WebClient wClient = new WebClient();
			responseData = wClient.DownloadData(URL);
			UTF8Encoding utf8 = new UTF8Encoding();
			String Lyrics = utf8.GetString(responseData);
			return ParseLyrics(Lyrics);
		}

		private static string ParseLyrics(string Lyrics)
		{
			string result = "";

			int infoIndex = Lyrics.IndexOf("<div id='info'>");
			if (infoIndex >= 0)
			{
				int endIndex = Lyrics.IndexOf("</div>");
				Lyrics = Lyrics.Remove(0, endIndex);

				// extract title
				Lyrics = Lyrics.Remove(0, Lyrics.IndexOf("<h1><a") + 6);
				Lyrics = Lyrics.Remove(0, Lyrics.IndexOf(">") + 1);
				string title = Decode(Lyrics.Substring(0, Lyrics.IndexOf("<")));

				// extract artist
				Lyrics = Lyrics.Remove(0, Lyrics.IndexOf("<h2><a") + 6);
				Lyrics = Lyrics.Remove(0, Lyrics.IndexOf(">") + 1);
				string artist = Decode(Lyrics.Substring(0, Lyrics.IndexOf("<")));

				result += "Guess title: '" + title + "' of '" + artist + "'\r\n\r\n";
			}

			int divStartIndex = Lyrics.IndexOf("<p>");
			if (divStartIndex == -1)
				return "Lyrics Not Found";

			Lyrics = Lyrics.Remove(0, divStartIndex);
			int divEndIndex = Lyrics.IndexOf("</p>");
			Lyrics = Lyrics.Remove(divEndIndex);

			Lyrics = Decode(Lyrics);

			result += Lyrics;

			if (result.Length == 0)
				result = "Lyrics Not Found.";
			return result;
		}

		private static string Decode(string text)
		{
			text = Regex.Replace(text, @"<br[\s/]*>|</p>", "", RegexOptions.IgnoreCase);
			text = Regex.Replace(text, @"<[^>]+>|</\w+>", "", RegexOptions.IgnoreCase);

			text = System.Web.HttpUtility.HtmlDecode(text);

			return text.Trim();
		}
	}
}
